﻿using System;
using System.Drawing;
using System.Windows.Forms;
//
using System.IO;
using System.Net;
using System.Drawing.Imaging;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Diagnostics;

// BingWallPaper, Copyright Mirosław M. Mączka.  All Rights Reserved. This code released under the terms of the Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

namespace BingWallPaper
{
    public partial class Form1 : Form
    {
        const int SPI_SETDESKWALLPAPER = 20;
        const int SPIF_UPDATEINIFILE = 0x01;
        const int SPIF_SENDWININICHANGE = 0x02;

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);
        //
        public string urlWallPaper = "";
        public string fileWallPaper = Environment.GetFolderPath(Environment.SpecialFolder.System) + @"\Temp\BingWallPaper.bmp";
        //
        public Form1()
        {
            InitializeComponent();
            this.Opacity = 0;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            timerOnLoad.Interval = 5000;
            timerOnLoad.Start();
        }

        private void timerOnLoad_Tick(object sender, EventArgs e)
        {
            timerOnLoad.Enabled = false;
            //
            webBrowser1.Url = new Uri("http://www.bing.com/");
            //
            if (!Utils.IsEwfActive()) { Application.Exit(); }
            //
            if (Utils.HasWirelessNetwork())
            {
                timer1.Interval = 2000;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //HtmlElementCollection hec = webBrowser1.Document.GetElementsByTagName("VIDEO");
            //var doc = sender as HtmlDocument;
            //HtmlElement imagetag = doc.GetElementFromPoint(e.MousePosition);
            //string sss = webBrowser1.Document.GetElementFromPoint(new Point(200, 200)).Name;
            //webBrowser1.Document.GetElementFromPoint(new Point(100, 100)).Style.Split(';');
            //"width: 654px; height: 472px; filter: ; opacity: 1; background-image: url(\"http://www.bing.com/az/hprichbg?p=rb%2fForthBridge_ROW1130911611.jpg\");"
            //" background-image: url(\"http://www.bing.com/az/hprichbg?p=rb%2fForthBridge_ROW1130911611.jpg\")"
            //string tag = imagetag.InnerHtml;
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            timer1.Enabled = true;
        }

        private int kount = 7;
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                //webBrowser1.Document.GetElementFromPoint(new Point(100, 100));
                urlWallPaper = ParseStyle.GetUrl(webBrowser1.Document.GetElementById("bgDiv").Style, "background-image");
                if ("" == urlWallPaper)
                {
                    kount--;
                    if (kount >= 0) return;
                }
                //
                if ("" == urlWallPaper) throw new Exception("\"\" == urlWallPaper");
                //
                WebRequest req = WebRequest.Create(urlWallPaper);
                WebResponse response = req.GetResponse();
                Stream stream = response.GetResponseStream();
                Image img = Image.FromStream(stream);
                stream.Close();
                //
                Size monitor = System.Windows.Forms.SystemInformation.PrimaryMonitorSize;
                double mProportion = (double)monitor.Width / monitor.Height;
                //double mProportion = (double)1280 / 1024;
                //
                double iProportion = (double)img.Width / img.Height;
                //
                if (mProportion < iProportion)
                {
                    int newWidth = (int)(img.Height * mProportion);
                    //
                    Bitmap b = new Bitmap(newWidth, img.Height);
                    Graphics g = Graphics.FromImage((Image)b);

                    g.DrawImage(img, new Rectangle(0,0, newWidth,img.Height), new Rectangle((img.Width-newWidth)/2,0, newWidth, img.Height), GraphicsUnit.Pixel);
                    g.Dispose();
                    //
                    img = (Image)b;

                }
                //
                File.Delete(fileWallPaper);
                img.Save(fileWallPaper, ImageFormat.Bmp);
                img.Dispose();
                //
                //
                RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);
                key.SetValue(@"WallpaperStyle", "2");
                key.SetValue(@"TileWallpaper", "0");
                SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, fileWallPaper, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
                //
                this.Close();
            }
            catch (Exception ee)
            {

                //MessageBox.Show(ee.Message + Environment.NewLine + ee.StackTrace, ee.Source);
                eventLog1.WriteEntry(string.Format("[{0}/{1}]\n{2}.", ee.Message, ee.Source, ee.StackTrace), EventLogEntryType.Error);
                this.Close();
            }
        }



    }
}
